#include "head.h"


// 返回0，表示验证成功
int loginVerify(int sockfd, char *name){
    // 小火车读取用户名字
    train_t *userName = (train_t *)calloc(1, sizeof(train_t));

    /* int ret = recv(sockfd, &userName->type, sizeof(userName->type), MSG_WAITALL); */
    
    
    int ret = getInstruction(sockfd, userName);  
    memcpy(name, userName->path, userName->len);
    ERROR_CHECK(ret, -1, "recv login message");
    
    if(ret <= 0){
        // 用户断开连接
        return -1;
    }
    /* printf("name : %s\n", userName->buf); */
    
    // 小火车读取用户密码
    train_t *userPsw = (train_t *)calloc(1, sizeof(train_t));

    getInstruction(sockfd, userPsw);

    struct spwd *userMess = getspnam(userName->path);
    if(userMess == NULL){
        printf("用户名错误\n");
        // 返回值用1表示
        return 1;
    }
    
    // 盐值为前四个$符之间的内容
    char salt[256] = {0};
    int index = 0;
    int count = 4;
    // 确认盐值
    while(count != 0){
        if(userMess->sp_pwdp[index] == '$'){
            count--;
        }
        index++;
    }
    memcpy(salt, userMess->sp_pwdp, index);

    struct crypt_data cdata;
    bzero(&cdata, sizeof(cdata));
    
    // 此函数线程安全
    char *hash = crypt_r(userPsw->path, salt, &cdata);
    
    // 密码判断
    if(strcmp(hash, userMess->sp_pwdp) != 0){
        printf("密码错误\n");
        // 用2表示密码错误
        return 2;
    }

    /* printf("hash : %s \n", crypt_r(userPsw->buf, salt, &cdata)); */
    /* printf("userpassword : %s\n", userMess->sp_pwdp); */
    
    
    // 身份核对无误，返回0;
    printf("身份验证通过\n");
    return 0;
}
